<!-- 添加课程评价 -->
<template>
    <div class="add-comment-container">
        <h2 class="comment-header">课程评价<span v-if="props.isNeedComment" class="comment-tips">提示：完成该慕课必须参与课程评价</span></h2>
        <template v-if="questionList && questionList.length">
            <div v-for="item in questionList" :key="item.id">
                <component 
                    :is="componentMap[item.questionType]"
                    page-type="answer"
                    :id="item.id"
                    :title="item.title"
                    :content="item.content"
                    :is-must="item.isMust"
                    :user-answer-list="item.userAnswerList"
                    placeholder="可以在此发表您对该课程的看法，至少输入2个字..."
                    :is-preview="isPreview"
                    @answer="setAnswer"/>
            </div>
        </template>
        <div class="submit-btn-wrap">
            <el-button class="srt-el-button srt-el-button--primary btn-h34" :disabled="!checkValid" @click="checkValidAssess">发表评价</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, watch, reactive } from 'vue';
import Confirm from '@/components/confirm/confirm.js';
// import Star from '@/components/star/star.vue';
import ScCompare from './sc-compare.vue';
import ShortTopic from './short-topic';
import { useStore } from 'vuex';

const store = useStore();

const emit = defineEmits(['refresh-detail']);

const props = defineProps({
    data: {
        type: Object,
        default: () => {}
    },
    assessInfo: { // 问卷及课程信息
        type: Object,
        default: () => {}
    },
    isNeedComment: { // 是否必须评价才算完成慕课
        type: Boolean,
        default: false
    },
    isPreview: { // 是否是预览状态
        type: Boolean,
        default: false
    }
})

// 获取当前用户信息
const currentUser = computed(() => {
    return store.state?.currentUser || {};
})

const questionList = ref([]);

const answerObj = reactive({});

const answerArr = ref([]);

const answerArrBak = ref([]);

const answerArrToValid = ref([]);

let userName = ref('');

let userId = ref('');

const questionObj = {}; // 题目Map{id：index}    [id]: [questionListIndex]

// // 评分维度
// const dimensionList = ref([
//     {
//         id: 1,
//         name: '教育目标',
//         rate: 0
//     },
//     {
//         id: 1,
//         name: '教材处理',
//         rate: 0
//     },
//     {
//         id: 1,
//         name: '教育程序',
//         rate: 0
//     },
//     {
//         id: 1,
//         name: '教材方法',
//         rate: 0
//     },
//     {
//         id: 1,
//         name: '教育表现',
//         rate: 0
//     },
//     {
//         id: 1,
//         name: '教材效果',
//         rate: 0
//     }
// ]);

// // 评论内容
// const comment = ref('');

const componentMap = {
    7: ScCompare, // 量表组合题
    // 6: ScaleChoice, // 量表单选题
    // 5: UploadTopic, // 上传题
    // 3: FillTopic, // 填空题
    // 9: FillTopic, // 填空题
    // 2: MultipleChoice, // 多选题
    // 1: SingleChoice, // 单选题
    8: ShortTopic // 简答
};

// 是否完整填写了评论内容
const checkValid = computed(() => {
    // let num = 0;
    // dimensionList.value.forEach(item => {
    //     if (item.rate) {
    //         num++;
    //     }
    // })
    // if (num >= dimensionList.value.length && !!comment.value && !!comment.value.trim()) {
    //     return true;
    // } else {
    //     return false;
    // }
    return true
})

// 答案更改
function setAnswer(data, type, id, isInit) { 
    if(Object.keys(data).length) {
        data.type = type;
        data.attr = {
            isMust: props.data.isMust
        }
        answerChange({...data}, id, isInit); 
    }
}

// 更新答案
function answerChange(data, id, isInit) { 
    let tempData = {};
    for(let keyword in (data || {})) {
        if(data[keyword] && data[keyword].answer) { // 答案不为空，暂存
            tempData[keyword] = {...data[keyword]};
        }
    }
    let isEdited = answerObj[id] && answerObj[id].isEdited !== 0 ? answerObj[id].isEdited : compareObj(answerObj[id], tempData, isInit);
    answerObj[id] = {
        ...tempData,
        attr: data.attr,
        type: data.type,
        isEdited
    }
}

function compareObj(obj1, obj2, isInit) {
    let obj = {}, isEdited = 0;
    if(isInit) {
        return isEdited;
    }
    if(!obj1) {
        obj1 = {};
    }
    for(let keyword in obj1) {
        if(!['attr', 'type', 'isEdited'].includes(keyword)) {
            obj[keyword] = obj1[keyword];
        }
    }
    let len1 = Object.keys(obj || {}).length, len2 = Object.keys(obj2 || {}).length;
    if(len1 !== len2) {
        isEdited = 2;
    } else {
        for(let key in obj) {
            if(!obj2[key] || obj[key].answer != obj2[key].answer) {
                isEdited = 2;
            }
        }
    }
    return isEdited;
}

// 提交需要数据结构处理
function getAnswerArr(state) {
    answerArrBak.value = answerArr.value || [];
    let temp = {};
    answerArr.value = [];
    answerArrToValid.value = [];
    // console.log('an++++', answerObj)
    for(let id in answerObj) {
        let tempObj = answerObj[id];
        if(!Object.keys(tempObj).length) {
            continue;
        }
        temp = {
            questionType: tempObj.type,
            questionId: id,
            indexList: [],
            isEdited: tempObj.isEdited,
        }
        for(let keyword in tempObj) {
            if(['type', 'attr', 'isEdited'].includes(keyword)) {
                continue;
            }
            let answer = tempObj[keyword].answer;
            if(answer) {
                temp.indexList.push({
                    questionIndex: keyword,
                    answer
                })
            }
        }
        if(state == 2 || temp.isEdited == 2 ) {
            answerArrToValid.value.push(temp);
        }
        // debugger
        if(temp.isEdited == 2) {
            answerArr.value.push(temp);
        }
    }
}

// 发表评价
function checkValidAssess () {
    if (props.isPreview) { // 预览状态下不能发表评价
        G_dispatchEvent('toast', { message: '预览状态下不可操作', type: 'error'});
        return;
    }
    getAnswerArr(2);

    // 答题数据小于等于0
    if (answerArrToValid.value.length <= 0) {
        G_dispatchEvent('toast', { message: '请完成全部项打分', type: 'error'});
        return;
    }
    
    let startValid = answerArrToValid.value.filter(item => item.questionType !== '8').length > 0;
    let commentValid = answerArrToValid.value.filter(item => item.questionType === '8').length > 0;
    // 每道题作答是否有效
    answerArrToValid.value && answerArrToValid.value.forEach(item => {
        if (item.indexList && item.indexList.length) {
            item.indexList.forEach(item2 => {
                if (item.questionType === '8') { // 是简答题      
                    if (!item2.answer || (item2.answer && !item2.answer.trim()) || (item2.answer && item2.answer.trim().length < 2)) {
                        commentValid = false;
                    }
                } else { // 量表题
                    let filterItem = questionList.value.filter(item3 => item3.id === item.questionId);
                    let len = filterItem[0]?.content?.row?.length || 0;
                    if (len !== item.indexList.length) {
                        startValid = false;
                    }
                }
            })
        } else {
            if (item.questionType === '8') {
                commentValid = false;
            } else {
                startValid = false;
            }
        }
    })
    if (!startValid) {
        G_dispatchEvent('toast', { message: '请完成全部项打分', type: 'error'});
        return;
    }
    if (!commentValid) {
        G_dispatchEvent('toast', { message: '请输入正确的评价内容', type: 'error'});
        return;
    }
    Confirm({
        title: '确认发表',
        text: '确定要发表此评价吗？发表后不可更改'
    }).then(ret => {
        submit();
    }).catch(err => {
        // 点击取消按钮触发
        if (err === 'cancel') {
          return false
        }
    })
}

function submit () {
    G_transmit('assessSaveAnswer', {
        data: {
            assessId: props.assessInfo.assessId || '',
            subBizId: props.assessInfo.subBizId || '',
            subBizType: props.assessInfo.subBizType || 'mooc',
            state: 2,
            items: answerArrToValid.value,
            userName: currentUser.value.name || '',
            // queryInvalid: true // 查询包括删除的
        }
    }).then((res) => {
        G_dispatchEvent('toast', { message: '评价成功', type: 'success'});
        refreshData();
    }).catch(_err => {
        console.log(_err);
    })
}

function refreshData () {
    setTimeout(() => {
        // 更新详情会触发更新列表
        emit('refresh-detail');
    }, 500)
}

watch(() => props.data, (newVal) => {
    // console.log(newVal.questionList, 'newVal.questionList');
    questionList.value = newVal.questionList;
}, {
    immediate: true,
    deep: true
})

</script>

<style lang="scss" scoped>
.add-comment-container {
    font-family: MicrosoftYaHei;
    .comment-header {
        font-size: 16px;
        font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
        font-weight: bold;
        color: var(--srt-color-black);
        .comment-tips {
            margin-left: 20px;
            // color: var(--srt-main-text-color);
            color: var(--srt-color-warning);
            font-size: 14px;
            font-weight: 400;
            // &::before {
            //     content: '\e67f';
            //     font-family: 'iconfont';
            //     font-size: 15px;
            //     color: var(--srt-color-warning);
            //     margin-right: 6px;
            // }
        }
    }
    .comment-content {
        margin-top: 30px;
    }
    .submit-btn-wrap {
        text-align: right;
        margin-top: 20px;
        .btn-h34 {
            font-size: 14px;
            padding: 0 24px;
            min-height: 34px;
        }
    }
}
</style>